<?php
include_once("../includes/common.php");
include_once("../class/User.class.php");
require_once("../islogin.php");

if ($islogin!=1){
    header('Location: /login.php');
    exit;
}

$menuavatar = !$user_info["message"]["avatar"] ? "/data/avatar/default.jpg" : $user_info["message"]["avatar"];
$pageName = "用户设置";


if(isset($_GET['saveuser'])){
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $avatar = trim(htmlspecialchars($_POST['avatar']));
        $nickname = trim(htmlspecialchars($_POST['nickname']));
        $phone = trim(htmlspecialchars($_POST['phone']));
        $birthday = trim(htmlspecialchars($_POST['birthday']));
        $blueid = trim(htmlspecialchars($_POST['blueid']));
        $gender = isset($_POST['gender']) ? intval($_POST['gender']) : null; // 确保性别字段有值
        $desc = trim(htmlspecialchars($_POST['desc']));

        $today = new DateTime();
        $inputDate = new DateTime($birthday);

        if ($inputDate > $today) {
            echo '<script>alert("生日不能大于今天！"); window.location.href = "/control/setting.php";</script>';
            exit;
        }

        if (empty($nickname) || empty($phone) || empty($birthday) || empty($blueid) || is_null($gender)) {
            echo '<script>alert("昵称、手机号、生日、小蓝书号和性别不能为空！"); window.location.href = "/control/setting.php";</script>';
            exit;
        }

        $res = json_decode($user->saveUserInfo($user_info['message']['user_id'], $avatar, $nickname, $phone, $birthday, $blueid, $gender, $desc),true);

        if ($res['status']==200) {
            header('Location: /control/setting.php');
            //echo '<script>alert("'.$res['message'].'"); window.location.href = "/control/setting.php";</script>';
            exit;
        }else{
            echo '<script>alert("'.$res['message'].'"); window.location.href = "/control/setting.php";</script>';
            exit;
        }


    }
}

if(isset($_GET['changepwd'])){
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $password = $_POST['oripwd'];
        $newpwd1 = $_POST['newpwd1'];
        $newpwd2 = $_POST['newpwd2'];

        if (empty($password) || empty($newpwd1) || empty($newpwd2)){
            $warn = 1;
        }else{
            if ($newpwd2==$newpwd1){
                $res = json_decode($user->changepwd($user_info['message']['user_id'], $password, $newpwd1),true);
                if($res['status']==200){
                    $success = 1;
                }else{
                    $error = 1;
                }
            }else{
                $error = 1;
                $res['message'] = '两次输入的密码不同！';
            }



        }


    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>

    <?php require_once('head.php'); ?>

    <link rel="stylesheet" href="/static/css/message.css" />
</head> 
<body>
    
<!--==================== Preloader Start ====================-->
  <div class="preloader">
    <div class="loader"></div>
  </div>
<!--==================== Preloader End ====================-->

<!--==================== Sidebar Overlay End ====================-->
<div class="side-overlay"></div>
<!--==================== Sidebar Overlay End ====================-->


<?php require_once('user_menu.php'); ?>
    <div class="dashboard-main-wrapper">

        <?php require_once('top_navbar.php'); ?>
        <div class="dashboard-body">
             
            <div class="card overflow-hidden">
                <div class="card-body p-0">


                    <div class="setting-profile px-24">
                        <div class="flex-between">
                            <div class="d-flex align-items-end flex-wrap mb-32 gap-24">

                            </div>
                        </div>
                        <ul class="nav common-tab style-two nav-pills mb-0" id="pills-tab" role="tablist">
                            <li class="nav-item" role="presentation">
                              <button class="nav-link active" id="pills-details-tab" data-bs-toggle="pill" data-bs-target="#pills-details" type="button" role="tab" aria-controls="pills-details" aria-selected="true">详细信息</button>
                            </li>
                            <li class="nav-item" role="presentation">
                              <button class="nav-link" id="pills-password-tab" data-bs-toggle="pill" data-bs-target="#pills-password" type="button" role="tab" aria-controls="pills-password" aria-selected="false">修改密码</button>
                            </li>
                        </ul>
                    </div>

                </div>
            </div>

            <div class="tab-content" id="pills-tabContent">
                <!-- My Details Tab start -->
                <div class="tab-pane fade show active" id="pills-details" role="tabpanel" aria-labelledby="pills-details-tab" tabindex="0">
                    <div class="card mt-24">
                        <div class="card-header border-bottom">
                            <h4 class="mb-4">详细信息</h4>
                            <p class="text-gray-600 text-15">快来设置你的详细信息吧 ~</p>
                        </div>
                        <div class="card-body">
                            <form action="?saveuser" method="post">
                                <div class="row gy-4">
                                    <div class="col-12">
                                        <label for="imageUpload" class="form-label mb-8 h6">头像</label>
                                        <div class="flex-align gap-22">
                                            <div class="avatar-upload flex-shrink-0">
                                                <input type='file' id="imageUpload" accept=".png, .jpg, .jpeg, .webp, .gif">
                                                <div class="avatar-preview">
                                                    <div id="profileImagePreview" style="background-image: url('<?php echo $menuavatar?>');">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="avatar-upload-box text-center position-relative flex-grow-1 py-24 px-4 rounded-16 border border-main-300 border-dashed bg-main-50 hover-bg-main-100 hover-border-main-400 transition-2 cursor-pointer">
                                                <label for="imageUpload" class="position-absolute inset-block-start-0 inset-inline-start-0 w-100 h-100 rounded-16 cursor-pointer z-1"></label>
                                                <span class="text-32 icon text-main-600 d-inline-flex"><i class="ph ph-upload"></i></span>
                                                <span class="text-13 d-block text-gray-400 text my-8">点击上传头像</span>
                                                <span class="text-13 d-block text-main-600">PNG, JPEG, SVG, WEBP 或者 GIF (最大 1080px1200px)</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6 col-xs-6" style="display: none">
                                        <label for="fname" class="form-label mb-8 h6">头像</label>
                                        <input value="<?php echo $user_info['message']['avatar']?>" id="upavatar" name="avatar" type="text" class="form-control py-11" placeholder="输入头像">
                                    </div>
                                    <div class="col-sm-6 col-xs-6">
                                        <label for="fname" class="form-label mb-8 h6">昵称</label>
                                        <input type="text" required maxlength="24" value="<?php echo $user_info['message']['nickname']?>" name="nickname" class="form-control py-11" id="fname" placeholder="输入昵称">
                                    </div>
                                    <div class="col-sm-6 col-xs-6">
                                        <label for="phone" class="form-label mb-8 h6">手机号</label>
                                        <input required value="<?php echo $user_info['message']['phone']?>" type="number" name="phone" class="form-control py-11" id="phone" placeholder="输入手机号">
                                    </div>
                                    <div class="col-sm-6 col-xs-6">
                                        <label for="role" class="form-label mb-8 h6">生日</label>
                                        <input required value="<?php echo $user_info['message']['birthday']?>" type="date" name="birthday" class="form-control py-11" id="role" placeholder="输入生日 Y-m-d">
                                    </div>
                                    <div class="col-sm-6 col-xs-6">
                                        <label for="zip" class="form-label mb-8 h6">小蓝书号</label>
                                        <input required value="<?php echo $user_info['message']['blue_id']?>" type="text" name="blueid" maxlength="15" class="form-control py-11" id="zip" placeholder="输入小蓝书号 数字/英文/英文+数字混合">
                                    </div>
                                    <div class="col-sm-6 col-xs-6">
                                        <label for="role" class="form-label mb-8 h6">性别</label><br>
                                        <input type="radio" name="gender" class="form-check-input" value="1" <?php echo $user_info['message']['gender']==1 ?'checked':''?>> 男
                                        <input style="margin-left: 20px" type="radio" name="gender" class="form-check-input" value="0" <?php echo $user_info['message']['gender']==0 ?'checked':''?>> 女
                                    </div>
                                    <div class="col-12">
                                        <div class="editor">
                                            <label class="form-label mb-8 h6">简介</label>
                                            <textarea maxlength="100" name="desc" class="form-control placeholder-14" style="height: 220px;line-height: 1.5;" placeholder="在这里输入你的简介 ~"><?php echo $user_info['message']['description']?></textarea>
                                        </div>
                                    </div>
                                    <div class="col-12">
                                        <div class="flex-align justify-content-end gap-8">
                                            <button type="submit" class="btn btn-main rounded-pill py-9">保 存</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <!-- My Details Tab End -->

                <!-- Password Tab Start -->
                <div class="tab-pane fade" id="pills-password" role="tabpanel" aria-labelledby="pills-password-tab" tabindex="0">
                    <div class="card mt-24">
                        <div class="card-header border-bottom">
                            <h4 class="mb-4">修改密码</h4>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <form action="?changepwd" method="post" id="passwordForm">
                                        <div class="row gy-4">
                                            <div class="col-12">
                                                <label for="current-password" class="form-label mb-8 h6">当前密码</label>
                                                <div class="position-relative">
                                                    <input value="<?php echo $password?>" type="password" name="oripwd" class="form-control py-11" id="current-password" placeholder="输入当前密码">
                                                    <span class="toggle-password position-absolute top-50 inset-inline-end-0 me-16 translate-middle-y ph ph-eye-slash" id="#current-password"></span>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <label for="new-password" class="form-label mb-8 h6">新密码</label>
                                                <div class="position-relative">
                                                    <input value="<?php echo $newpwd1?>" type="password" name="newpwd1" class="form-control py-11" id="new-password" placeholder="输入新密码">
                                                    <span class="toggle-password position-absolute top-50 inset-inline-end-0 me-16 translate-middle-y ph ph-eye-slash" id="#new-password"></span>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <label for="confirm-password" class="form-label mb-8 h6">确认新密码</label>
                                                <div class="position-relative">
                                                    <input value="<?php echo $newpwd2?>" type="password" name="newpwd2" class="form-control py-11" id="confirm-password" placeholder="再次输入新密码">
                                                    <span class="toggle-password position-absolute top-50 inset-inline-end-0 me-16 translate-middle-y ph ph-eye-slash" id="#confirm-password"></span>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <label class="form-label mb-8 h6">密码要求:</label>
                                                <ul class="list-inside">
                                                    <li class="text-gray-600 mb-4">密码不得少于六位！</li>
                                                    <li class="text-gray-600 mb-4">两次输入的密码需要匹配！</li>
                                                </ul>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <div class="col-12">
                                    <div class="flex-align justify-content-end gap-8">
                                        <button onclick="submitchangepwd()" type="submit" class="btn btn-main rounded-pill py-9">修 改</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Password Tab End -->

            </div>
        </div>

        <?php require_once('footer.php'); ?>
    </div>

<script src="/static/js/message.min.js"></script>
<?php require_once('foot.php'); ?>

<script>
    function submitchangepwd() {
        document.getElementById("passwordForm").submit();
    }
</script>
<script>
<?php if($warn==1){?>
    Qmsg.warning("原密码和新密码不得为空!");
<?php }?>

<?php if($error==1){?>
    Qmsg.error("<?php echo $res['message']; ?>");
<?php }?>


<?php if($success==1){?>
    Qmsg.success("修改成功！");


    setTimeout(function() {
    window.location.href = '/control/setting.php';
    }, 1000);
<?php }?>
</script>
    <script>
        // ============================= Avatar Upload js ============================= 
        function uploadImageFunction(imageId, previewId, inputId) {
            $(imageId).on('change', function () {
                var input = this; // 'this' is the DOM element here
                if (input.files && input.files[0]) {
                    var file = input.files[0];
                    var reader = new FileReader();

                    reader.onload = function(e) {
                        // 预览图片
                        $(previewId).css('background-image', 'url(' + e.target.result + ')');
                        $(previewId).hide();
                        $(previewId).fadeIn(650);

                        // 创建FormData对象用于文件上传
                        var formData = new FormData();
                        formData.append('file', file);
                        formData.append('avatar', 1); // 增加 avatar 字段并设置值为 1

                        // 使用Ajax上传图片
                        $.ajax({
                            url: '/api/upload.php', // 上传API的URL
                            type: 'POST',
                            data: formData,
                            processData: false, // 防止jQuery处理数据
                            contentType: false, // 不设置内容类型
                            success: function (response) {
                                var res = response;
                                if (res.status == 200) {
                                    // 更新背景图
                                    $(previewId).css('background-image', 'url(' + res.message + ')');

                                    // 将返回的图片地址填入input中
                                    $(inputId).val(res.message);

                                    // 处理上传成功逻辑
                                    var fileType = file.type;
                                    if (fileType.startsWith("image")) {
                                        uploadedImageCount++; // 增加图片数量
                                    } else if (fileType === "video/mp4") {
                                        uploadedMp4Exists = true; // 标记已经上传MP4视频
                                    }

                                    // 调用其他逻辑（如显示图片）
                                    displayUploadedImages(res.message, file);
                                } else {
                                    // 上传失败处理
                                    Qmsg.error(res.message);
                                }
                            },
                            error: function () {
                                // 处理上传错误
                                Qmsg.error("An error occurred while uploading the file.");
                            }
                        });
                    };

                    reader.readAsDataURL(file);
                }
            });
        }

        // 调用函数，并指定输入框的ID
        uploadImageFunction('#coverImageUpload', '#coverImagePreview', '#upavatar');
        uploadImageFunction('#imageUpload', '#profileImagePreview', '#upavatar');




    </script>

    </body>
</html>